//
//  NetworkHandeler.m
//  UI19_网络封装(delegate回调)
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetworkHandeler.h"

@implementation NetworkHandeler



// 通过 NSURLSession 实现网络请求

- (void)networkHandelerJSONWithURL:(NSString *)urlStr{

    // 若字符串中含有中文等字符, 先将字符串进行转码
    NSString *tempstr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];   // URLQueryAllowedCharacterSet 查询.
    
    NSLog(@"%@", tempstr);
    
    
    // URL
    NSURL *url = [NSURL URLWithString:tempstr];
    
    // session
    NSURLSession *session = [NSURLSession sharedSession];
    
    
    // task
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 返回主线程 (一般耗时的放在子线程)
        dispatch_async(dispatch_get_main_queue(), ^{
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        if ([self.delegate respondsToSelector:@selector(handelerDidComplete:)]) {
            
            [self.delegate handelerDidComplete:result];
        }

        });
        
                
    }];
    

    [task resume];
}





// 方法实现

+ (void)handelerJSONWithURL:(NSString *)urlStr delegate:(id<NetworkHandelerDelegate>)delegate{

    
    NetworkHandeler *handeler = [[NetworkHandeler alloc] init];
    
    handeler.delegate = delegate;
    
    [handeler networkHandelerJSONWithURL:urlStr];

}


@end
